import Cookies from 'js-cookie'
import defaultSettings from '@/settings'
// 缓存模板
const cacheTemplate = function(flag) {
    return {

        set(key, value) {
            const storage = window[flag ? 'sessionStorage' : 'localStorage'];
            const skey = defaultSettings.cacheSuffix + key;
            if (storage) {
                storage.setItem(skey, value);
            } else {
                Cookies.set(skey, value);
            }
        },

        get(key) {
            const storage = window[flag ? 'sessionStorage' : 'localStorage'];
            const skey = defaultSettings.cacheSuffix + key;
            if (storage) {
                return storage.getItem(skey);
            } else {
                return Cookies.get(skey);
            }
        },

        remove(key) {
            const storage = window[flag ? 'sessionStorage' : 'localStorage'];
            const skey = defaultSettings.cacheSuffix + key;
            if (storage) {
                storage.removeItem(skey);
            } else {
                return Cookies.remove(skey);
            }
        },

        setJSON(key, jsonValue) {
            this.set(key, JSON.stringify(jsonValue))
        },

        getJSON(key) {
            const value = this.get(key)
            return JSON.parse(value)
        }
    }
}

export default {
    /**
     * 会话级缓存
     */
    session: cacheTemplate(true),
    /**
     * 本地缓存
     */
    local: cacheTemplate(false)
}